package com.framework.bas.web.provider.impl;

import java.util.ArrayList;
import java.util.List;

import com.framework.bas.bs.IPlmBasBS;
import com.framework.bas.param.QueryParam;
import com.framework.bas.util.SpringUtil;
import com.framework.bas.web.controller.PageSupport;
import com.framework.bas.web.provider.IPlmQueryProvider;

@SuppressWarnings("unchecked")
public abstract class AbsPlmQueryProvider implements IPlmQueryProvider {
	
	// 默认不分页
	private int pageSize = -1;
	
	private PageSupport pageSupport;
	
	private static IPlmBasBS plmBasBS = null;

	protected AbsPlmQueryProvider() {
	}
	
	protected IPlmBasBS getPlmBasBS() {
		if (plmBasBS == null) {
			plmBasBS = (IPlmBasBS) SpringUtil.getBean(IPlmBasBS.BEAN_ID);
		}
		return plmBasBS;
	}
	
	public List queryPageData(boolean querySize) {
		return (List) doQueryData(querySize);
	}
	
	public PageSupport queryPageData() {
		return (PageSupport) doQueryData(true);
	}

	protected Object doQueryData(boolean querySize) {
		QueryParam[] qp = getQueryParam(querySize);
		List<Object> result = new ArrayList<Object>();
		if (querySize) {
			result.add(getPlmBasBS().query(qp[0]));
			result.add(new Integer(getPlmBasBS().querySize(qp[1])));
			this.pageSupport.setTotalRecord(((Integer) (result.get(1))).intValue());
			int totalPage = this.pageSupport.getTotalRecord() / getPreferPageSize();      
            if (this.pageSupport.getTotalRecord() % getPreferPageSize() > 0)
            	totalPage++;
			this.pageSupport.setTotalPage(totalPage);
			this.pageSupport.setResultList((List<Object>)result.get(0));
			return this.pageSupport;
		} else {
			result.add(getPlmBasBS().query(qp[0]));
			return result;
		}
	}

	protected int getPreferPageSize() {
		if (pageSize <= 0) {
			return pageSupport.getPageSize();
		}
		return pageSize;
	}
	
	public PageSupport getPageSupport() {
		return pageSupport;
	}

	public void setPageSupport(PageSupport pageSupport) {
		this.pageSupport = pageSupport;
	}

	/**
	 * 返回记录查询和记录数查询参数数组。
	 * 
	 * @param cdataset
	 * @param rdataset
	 * @return
	 */
	protected abstract QueryParam[] getQueryParam(boolean querySize);

}
